<?php

class auth
{
	var $def_redir='cmap.php';
	var $def_auth='auth.php';
	var $auth_type_ = 0;			// 0 - monitor 1-admin

	var $cookie_name = 'AuthAsud';
	var $sessid = '';

	function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') 
	{ 
    	$str = ''; 
    	$count = strlen($charset); 
    	while ($length--) 
    	{ 
        	$str .= $charset[mt_rand(0, $count-1)]; 
    	} 
    	return $str; 
	} 

	function setDefRedir($_redir)
	{
		$this->def_redir = $_redir;
	}

	function authentication($dbh, $post)
	{
		if (isset($post['login']) && isset($post['password']) && isset($post['submit']))
		{

			$sth = $dbh->prepare('select * from users where u_login=:login and u_password=PASSWORD(:password) LIMIT 1');

			if ($sth->execute(array(':login' => rtrim(ltrim(addslashes($post['login']))),':password' => rtrim(ltrim(addslashes($post['password']))) )))
			{
				$alldb = $sth->fetchAll(PDO::FETCH_ASSOC); 

				if (empty($alldb))
					return false;
				
				$user['uid'] = $alldb[0]['u_id'];
				$user['login'] = $alldb[0]['u_login'];
				$user['name'] = $alldb[0]['u_name'];
				$user['type'] = $alldb[0]['u_p_admin'];
				$user['rule'] = $alldb[0]['u_p_edit'];

				$this->sessid = $this->randString(10);

				try
                {
   					$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
					$dbh->beginTransaction();

					try
					{
						$sth = $dbh->prepare('delete from session where idsession = ?');
						$sth->execute(array($this->sessid));
   					}
					catch (Exception $e)
					{
							// ok no active session
					}

					$sth = $dbh->prepare('insert into session (idsession, session_data) values (?,?)');
					$sth->execute(array($this->sessid, base64_encode(serialize($user))));

					$dbh->commit();

				}
				catch (Exception $e)
				{
					$dbh->rollBack();
					return false;
				}

				return true;
			}
			else                                                   
			{
				return false;
			}
		}
	}

	function getRedir()
	{
		return 'Location: ' . $this->def_redir;
	}

	function getAuthRedir()
	{
		return 'Location: ' . $this->def_auth.'?redir=' . $this->def_redir;
	}

	function getCookie()
	{
		$cookie['name'] = $this->cookie_name;
		$cookie['value'] = $this->sessid;
		return $cookie;
	}

	function isauth($dbh, $cookies, $admin = true)
	{
		if (isset($cookies[$this->cookie_name]))
		{

			$sth = $dbh->prepare('select * from session where idsession=:sessid LIMIT 1');

			if ($sth->execute(array(':sessid' => rtrim(ltrim(addslashes($cookies[$this->cookie_name]))))))
			{
				
				$alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

				if (empty($alldb))
					return false;

				$user_info = unserialize(base64_decode($alldb[0]['session_data']));

				if ((intval($user_info['type']) == 0) && $admin)
				{
					return false;
				}

				return $user_info;
			}
		}

		$this->sessid = '';
		return false;
	}
}

?>
